package com.bestcem.xm.ticket.service.impl;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.ticket.controller.param.ticket.config.CreateConfigParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.TicketTemplateParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.UpdateConfigParam;
import com.bestcem.xm.ticket.dao.TicketTemplateDao;
import com.bestcem.xm.ticket.entity.mongo.TicketTemplate;
import com.bestcem.xm.ticket.service.TicketTemplateService;
import com.bestcem.xm.ticket.service.convert.TicketTemplateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author liheng
 * @version v1.0
 * @date 2021/8/20 14:31
 */
@Slf4j
@Service
public class TicketTemplateServiceImpl implements TicketTemplateService {

    @Resource
    private TicketTemplateDao ticketTemplateDao;

    @Resource
    private TicketTemplateMapper ticketTemplateMapper;

    @Override
    public ServiceResult<String> createTicketTemplate(String ticketConfigId, CreateConfigParam param) {
        List<TicketTemplateParam> ticketTemplate = param.getTicketTemplate();

        if (CollectionUtils.isEmpty(ticketTemplate)) {
            if (log.isInfoEnabled()) {
                log.info("创建工单处理模板, ticketTemplate: {}", ticketTemplate);
            }
            return ServiceResult.failWithCode(ReqErrorCodeEnum.PARAM_LOST, "缺少必要参数");
        }

        TicketTemplateParam ticketTemplateParam = ticketTemplate.get(0);
        ticketTemplateParam.setTicketConfigId(ticketConfigId);
        ticketTemplateParam.setOrgId(param.getOrgId());
        ticketTemplateParam.setUserId(param.getUserId());
        TicketTemplate saveEntity = ticketTemplateMapper.paramToEntity(ticketTemplateParam);
        return ServiceResult.success(ticketTemplateDao.saveTicketTemplate(saveEntity).getId());
    }

    @Override
    public void updateTemplateRule(String ticketConfigId, UpdateConfigParam param) {
        List<TicketTemplateParam> ticketTemplates = Optional.ofNullable(param.getTicketTemplate()).orElse(new ArrayList<>(2));

        for (TicketTemplateParam ticketTemplateParam : ticketTemplates) {

            TicketTemplate ticketTemplate = ticketTemplateMapper.paramToEntity(ticketTemplateParam);
            String id = ticketTemplate.getId();
            if (Objects.nonNull(id)) {

                TicketTemplate entity = ticketTemplateDao.updateTemplate(id, ticketTemplate);
            } else {
                ticketTemplate.setTicketConfigId(ticketConfigId);
                TicketTemplate entity = ticketTemplateDao.saveTicketTemplate(ticketTemplate);
            }

        }

    }

}
